package org.example.jwt;

import com.alibaba.fastjson.JSONObject;
import org.springframework.util.DigestUtils;

import java.util.Base64;

/**
 * @version: java version 23
 * @Author: 韩学新
 * @description:
 * @date: 2025-06-10 下午7:38
 */
public class jwtDemo {
    public static void main() {


        JSONObject header = new JSONObject();
        header.put("Alg", "HS256");
        JSONObject payLoad = new JSONObject();
        payLoad.put("userName", "huawei");
        payLoad.put("userId", "123456");
        payLoad.put("userAge", "21");
        payLoad.put("time", System.currentTimeMillis());

        //Base64编码
        String jwtHeader = Base64.getEncoder().encodeToString(header.toJSONString().getBytes());
        String jwtPayLoad = Base64.getEncoder().encodeToString(payLoad.toJSONString().getBytes());

        String signingKey = "hxuexin";
        String sign = DigestUtils.md5DigestAsHex((payLoad.toJSONString() + signingKey).getBytes());
        String jwt = jwtHeader + "." + jwtPayLoad + "." + sign;
        System.out.println(jwt);

        System.out.println("======================================================================");
        //解密操作
        String payLoadStr = new String(Base64.getDecoder().decode(jwt.split("\\.")[1]));
        String jwtSign = jwt.split("\\.")[2];
        System.out.println(payLoadStr);
        System.out.println(jwtSign.equals(sign));
    }
}

